package com.insight.mapper;

import com.insight.dto.collection.CollectionTaskResponse;
import com.insight.dto.collection.FailedTableInfo;
import com.insight.entity.CollectionTask;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import org.mapstruct.*;

import java.util.List;
import java.util.ArrayList;

/**
 * CollectionTask MapStruct映射器
 * 自动生成实体与DTO之间的映射代码
 *
 * @author Insight Team
 */
@Mapper(componentModel = "spring",
        nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE,
        nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS)
public interface CollectionTaskMapper {

    /**
     * Entity → Response
     * 将采集任务实体转换为响应DTO
     */
    @Mapping(target = "datasourceId", source = "dataSource.id")
    @Mapping(target = "datasourceName", source = "dataSource.name")
    @Mapping(target = "type", source = "collectionType")
    @Mapping(target = "totalTables", source = "tablesTotal")
    @Mapping(target = "completedTables", source = "tablesCollected")
    @Mapping(target = "failedTables", expression = "java(parseFailedTables(task.getFailedTables()))")
    CollectionTaskResponse toResponse(CollectionTask task);

    /**
     * Entity列表 → Response列表
     */
    List<CollectionTaskResponse> toResponseList(List<CollectionTask> tasks);

    /**
     * 解析失败表JSON字符串为对象列表
     */
    default List<FailedTableInfo> parseFailedTables(String failedTablesJson) {
        if (failedTablesJson == null || failedTablesJson.isEmpty()) {
            return new ArrayList<>();
        }
        try {
            return JSON.parseObject(failedTablesJson, new TypeReference<List<FailedTableInfo>>() {});
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }
}
